<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '@vben/plugins/src/vxe-table/types';

import type { RowType } from './qrtzJob.data';

import { ref } from 'vue';

import { AccessControl } from '@vben/access';
import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { AntDesignOutLined } from '@vben/icons';

import { message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  qrtzJobDelApi,
  qrtzJobQueryByIdApi,
  qrtzJobQueryPageListApi,
} from '#/api/quartz/qrtzJob';
import { SparkDescriptions } from '#/components';
import { queryDictOptionsApi, useDictionaries } from '#/utils';
import QrtzJobLogList from '#/views/quartz/qrtzJobLog/QrtzJobLogList.vue';

import QrtzJobFormModal from './modules/QrtzJobFormModal.vue';
import { DetailsColumns } from './qrtzJob.data.ts';

const { translateValue } = useDictionaries([
  'status',
  'yes_or_no',
  'qrtz_execute_tactics',
]);

const detailsRef = ref();

const formOptions: VbenFormProps = {
  layout: 'horizontal',
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
  showCollapseButton: false,
  actionButtonsReverse: false,
  showDefaultActions: true,
  submitOnChange: false,
  submitOnEnter: false,
  commonConfig: {
    colon: true,
    labelWidth: 100,
  },
  schema: [
    {
      component: 'Input',
      label: '任务名称',
      fieldName: 'jobName',
      componentProps: {
        placeholder: '请输入任务名称',
      },
    },
    {
      component: 'ApiSelect',
      label: '状态',
      fieldName: 'status',
      componentProps: {
        placeholder: '请选择状态',
        allowClear: true,
        showSearch: true,
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: item.itemText,
            value: Number.parseInt(item.itemVal),
          }));
        },
        api: queryDictOptionsApi,
        params: {
          dictCode: 'status',
        },
      },
    },
  ],
};

const gridOptions: VxeGridProps<RowType> = {
  height: 'auto',
  toolbarConfig: {
    slots: {
      buttons: 'toolbar-buttons',
    },
  },
  columns: [
    { title: '序号', type: 'seq', width: 50, fixed: 'left', align: 'center' },
    {
      title: '任务名称',
      field: 'jobName',
      align: 'center',
      minWidth: 100,
    },
    {
      title: '调用方法',
      field: 'invokeTarget',
      align: 'center',
      minWidth: 200,
    },
    {
      title: 'cron表达式',
      field: 'cronExpression',
      align: 'center',
      minWidth: 100,
    },
    {
      title: '执行策略',
      field: 'misfirePolicy',
      align: 'center',
      minWidth: 100,
      cellRender: {
        name: 'CellDict',
        attrs: {
          dictCode: 'qrtz_execute_tactics',
          translateValue,
        },
      },
    },
    {
      title: '并发执行',
      field: 'concurrent',
      align: 'center',
      minWidth: 100,
      cellRender: {
        name: 'CellDict',
        attrs: {
          dictCode: 'yes_or_no',
          translateValue,
        },
      },
    },
    {
      title: '状态',
      field: 'status',
      align: 'center',
      minWidth: 100,
      cellRender: {
        name: 'CellDict',
        attrs: {
          dictCode: 'status',
          translateValue,
        },
      },
    },
    {
      title: '备注信息',
      field: 'remark',
      align: 'center',
      minWidth: 100,
    },
    {
      title: '主键',
      field: 'id',
      align: 'center',
      minWidth: 100,
      visible: false,
    },
    {
      title: '创建人',
      field: 'createBy',
      align: 'center',
      minWidth: 100,
      visible: false,
    },
    {
      title: '创建时间',
      field: 'createTime',
      align: 'center',
      minWidth: 100,
    },
    {
      title: '更新人',
      field: 'updateBy',
      align: 'center',
      minWidth: 100,
      visible: false,
    },
    {
      title: '更新时间',
      field: 'updateTime',
      align: 'center',
      minWidth: 100,
      visible: false,
    },
    {
      title: '操作',
      field: 'action',
      align: 'center',
      minWidth: 210,
      fixed: 'right',
      slots: {
        default: 'action',
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        return await qrtzJobQueryPageListApi({
          pageNo: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
};
const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions });
const [FromModal, formModalApi] = useVbenModal({
  connectedComponent: QrtzJobFormModal,
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      gridApi.query();
    }
  },
});
const [LogDrawer, logDrawerApi] = useVbenDrawer({
  title: '执行日志',
  connectedComponent: QrtzJobLogList,
});
async function handlerAdd() {
  formModalApi.setData({ id: undefined });
  formModalApi.open();
}
async function handlerEdit(row) {
  formModalApi.setData({ id: row.id });
  formModalApi.open();
}
async function handlerDel(row) {
  const msg = await qrtzJobDelApi(row.id);
  message.success(msg);
  await gridApi.query();
}
async function handlerDetails(row) {
  detailsRef.value.open({ id: row.id }, DetailsColumns);
}
async function handlerLog(row) {
  logDrawerApi.setData(row);
  logDrawerApi.open();
}
</script>

<template>
  <Page auto-content-height>
    <FromModal class="w-[50%]" />
    <LogDrawer class="w-[70%]" />
    <SparkDescriptions
      class="w-[60%]"
      title="定时任务详情"
      ref="detailsRef"
      :api="qrtzJobQueryByIdApi"
    />
    <Grid>
      <template #toolbar-buttons>
        <a-button
          v-access:code="'quartz:qrtzJob:add'"
          type="primary"
          class="mr-2"
          @click="handlerAdd()"
        >
          新增
        </a-button>
      </template>
      <template #action="{ row }">
        <a-button
          v-access:code="'quartz:qrtzJob:edit'"
          type="link"
          size="small"
          @click="handlerEdit(row)"
        >
          编辑
        </a-button>
        <a-popconfirm
          cancel-text="再想想"
          title="您确定要删除吗?"
          @confirm="handlerDel(row)"
        >
          <a-button
            v-access:code="'quartz:qrtzJob:del'"
            type="link"
            danger
            size="small"
          >
            删除
          </a-button>
        </a-popconfirm>
        <a-dropdown>
          <template #overlay>
            <a-menu>
              <AccessControl :codes="['quartz:qrtzJob:details']" type="code">
                <a-menu-item key="1" @click="handlerDetails(row)">
                  详情
                </a-menu-item>
              </AccessControl>
              <AccessControl :codes="['quartz:qrtzJobLog:query']" type="code">
                <a-menu-item key="2" @click="handlerLog(row)">
                  执行日志
                </a-menu-item>
              </AccessControl>
            </a-menu>
          </template>
          <a-button
            v-access:code="'quartz:qrtzJob:more'"
            size="small"
            type="link"
            @click.prevent
          >
            更多
            <AntDesignOutLined />
          </a-button>
        </a-dropdown>
      </template>
    </Grid>
  </Page>
</template>
